package com.kevms.phonewars;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/** 
* @class MySQLiteHelper
* 
* @brief SQLiteOpenHelper used to handle transactions
* between the internal database and the application.
* 
* This SQLiteOpenHelper provides an interface to the
* internal database through a series of functions
* that performs transactions with the SQLite Database.
*/ 
public class MySQLiteHelper extends SQLiteOpenHelper {

	public static final String DB_NAME = "phonewars.db";
	
	// Tables
	public static final String TABLE_PREF = "Preferences";
	
	// Columns
	public static final String ID = "_id";
	public static final String PREF_BGCOLOR = "bgcolor";
	public static final String PREF_PICPATH = "picpath";
	
	public static MySQLiteHelper instance;
	
	// SQLite create statements
	String CREATE_TABLE_PREF = "CREATE TABLE Preferences ( "
		+ "_id     INTEGER primary key AUTOINCREMENT,"
		+ "bgcolor INTEGER not null,"
		+ "picpath TEXT"
		+ ");";

	public static MySQLiteHelper getInstance(Context context) {
		if(instance == null) {
			instance = new MySQLiteHelper(context);
		}
		return instance;
	}
	
	private MySQLiteHelper(Context context) {
		super(context, DB_NAME, null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		try 
		{
			// Enable foreign key constraints
		    db.execSQL("PRAGMA foreign_keys = ON;");
			
			db.execSQL(CREATE_TABLE_PREF);
			
			seedTables(db);
		}
		catch (Exception e) 
		{
			Log.e("ERROR", e.toString());
		}
	}

	public void seedTables(SQLiteDatabase db) {
		ContentValues values = new ContentValues();
		values.put(PREF_BGCOLOR, 0);
	    db.insert(TABLE_PREF, null, values);
	}
	
	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		Log.w(MySQLiteHelper.class.getName(),
				"Upgrading database from version " + oldVersion + " to "
						+ newVersion + ", which will destroy all old data");
		db.execSQL("DROP TABLE IF EXISTS " + TABLE_PREF);
		onCreate(db);
	}
	
	public int getBgColor(SQLiteDatabase db) {
		Cursor cur = db.rawQuery("Select bgcolor from Preferences", null);
		if(cur.getCount() > 0) {
			cur.moveToFirst();
			return cur.getInt(0);
		}
		return 0;
	}
	
	public void setBgColor(SQLiteDatabase db, int bgcolor) {
		ContentValues args = new ContentValues();
		args.put(PREF_BGCOLOR, bgcolor);
		db.update(TABLE_PREF, args, null, null);
	}
	
	public String getPicPath(SQLiteDatabase db) {
		Cursor cur = db.rawQuery("Select picpath from Preferences", null);
		if(cur.getCount() > 0) {
			cur.moveToFirst();
			return cur.getString(0);
		}
		return null;
	}
	
	public void setPicPath(SQLiteDatabase db, String path) {
		ContentValues args = new ContentValues();
		args.put(PREF_PICPATH, path);
		db.update(TABLE_PREF, args, null, null);
	}
}